import { Component, Input, OnInit, ViewChild }  from '@angular/core';
import { STColumn, STComponent, STPage, STReq } from "@delon/abc";
import { DeviceService }                        from "../../device.service";
import { _HttpClient, ModalHelper }             from "@delon/theme";
import { DeviceViewBonusStaffListComponent }    from "./staff-list/staff-list.component";
import { Device }                               from "@shared/model/device-dto";
import { Staff }                                from "@shared/model/staff-dto";
import { Bonus }                                from "@shared/model/bonus";
import { NzMessageService }                     from "ng-zorro-antd";

@Component({
    selector   : 'app-device-view-bonus',
    templateUrl: './bonus.component.html',
})
export class DeviceViewBonusComponent implements OnInit
{
    
    @Input()
    device: Device;
    page: STPage = {
        show: false
    };
    req: STReq = {
        params: {}
    };
    data: Array<Bonus> = [];
    @ViewChild('st', { static: false }) st: STComponent;
    columns: STColumn[] = [
        { title: '', type: 'img', width: '50px', index: 'imageUrl' },
        { title: '联系人', index: 'userName', width: 240 },
        { title: '金额（元）', render: 'amount', width: 240, index: 'amount' },
        { title: '备注', index: 'remark' },
        {
            title  : '操作',
            width  : 240,
            buttons: [
                {
                    text: '删除', type: 'del', click: record =>
                    {
                        if ( record.id )
                        {
                            this.http.delete(`api/devices/bonus/${ record.id }`).subscribe(() =>
                            {
                                const index = this.data.findIndex(value => value.id === record.id);
                                this.data.splice(index, 1);
                                this.st.reload()
                            })
                        }
                        else
                        {
                            const index = this.data.findIndex(value => value.userId === record.userId);
                            this.data.splice(index, 1);
                            this.st.reload()
                        }
                    }
                },
            ]
        }
    ];
    
    constructor( private service: DeviceService, private modal: ModalHelper, private http: _HttpClient, private msgSrv: NzMessageService ) { }
    
    ngOnInit()
    {
        this.http.get<Array<Bonus>>(`api/devices/bonus/${ this.device.id }`).subscribe(value => this.data = value)
    }
    
    add()
    {
        this.modal.createStatic(DeviceViewBonusStaffListComponent, {
            deviceId: this.device.id,
            selected: this.data
        }).subscribe(( value: Array<Staff> ) =>
        {
            value.forEach(item => this.data.push({
                amount  : 0.0,
                deviceId: this.device.id,
                remark  : "",
                userId  : item.id,
                userName: item.userName,
                imageUrl: item.imageUrl
            }));
            this.st.reload()
        })
    }
    
    save()
    {
        this.http.post("api/devices/bonus/many", this.data, { deviceId: this.device.id }).subscribe(value =>
        {
            this.data = value;
            this.msgSrv.info("分成信息保存成功");
            this.http.get<Array<Bonus>>(`api/devices/bonus/${ this.device.id }`).subscribe(value => this.data = value)
        })
    }
    
    amountChane( index, item )
    {
        this.data[index] = item
    }
    
    formatterDollar = ( value: number ) => `￥ ${ value }`;
    parserDollar = ( value: string ) => value.replace('￥ ', '');
    
    maxAmount = item =>
    {
        let sum = 0;
        this.data.forEach(( value, index ) =>
        {
            if ( item.userId != value.userId )
                sum += value.amount
        });
        return this.device.price - sum
    }
    
}
